<?php

use yii\db\Migration;

/**
 * Class m220416_133208_user
 */
class m220416_133208_user extends Migration
{
    const TB_USER = '{{%user}}'; // 用户表

    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {
        $userOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $userOptions = 'CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE=InnoDB AUTO_INCREMENT=1';
        }

        $this->createTable(self::TB_USER, [
            'id' => $this->primaryKey()->unsigned()->unique(),
            'country_code' => $this->smallInteger()->unsigned()->notNull()->defaultValue(86)->comment('国家代码'),
            'mobile' => $this->bigInteger(11)->unsigned()->notNull()->defaultValue(0)->comment('手机号'),
            'nickname' => $this->string(20)->notNull()->defaultValue('')->comment('昵称'),
            'avatar' => $this->string(255)->notNull()->defaultValue('')->comment('头像链接地址'),
            'password_hash' => $this->string(72)->notNull()->comment('账号密码'),
            'password_salt' => $this->char(20)->notNull()->comment('密码加密盐'),
            'access_token' => $this->string(32)->unique()->notNull()->comment('API登录令牌'),
            'access_token_expire' => $this->bigInteger()->unsigned()->notNull()->defaultValue(0)->comment('API登录令牌有效时长'),
            'status' => $this->boolean()->notNull()->defaultValue(10)->comment('账号状态：-1已注销，0黑名单，10激活'),

            'created_at' => $this->dateTime()->notNull(),
            'updated_at' => $this->dateTime()->notNull(),
        ], $userOptions);
        // 创建手机号为索引
        $this->createIndex('idx-mobile', self::TB_USER, ['mobile', 'country_code', 'status']);
        // 创建昵称为索引
        $this->createIndex('idx-nickname', self::TB_USER, ['nickname', 'status']);
    }

    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        if (YII_ENV_DEV) {
            // 如果是测试环境 删除用户表
            $this->dropTable(self::TB_USER);
            return true;
        }
        echo "m220416_133208_user cannot be reverted.\n";

        return false;
    }
}
